package com.whfc.fuum.redis.impl;

import com.whfc.common.util.JSONUtil;
import com.whfc.fuum.dto.SysDeptDTO;
import com.whfc.fuum.redis.SysDeptRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-11-09 17:07
 */
@Repository
public class SysDeptRedisDaoImpl implements SysDeptRedisDao {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SYS_DEPT_KEY = "sys-dept-cache";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void setSysDept(Integer deptId, SysDeptDTO sysDept) {
        logger.info("设置组织机构缓存,deptId:{}, sysDeptId:{}", deptId, sysDept);
        String value = JSONUtil.toString(sysDept);
        redisTemplate.opsForHash().put(SYS_DEPT_KEY, String.valueOf(deptId), value);
    }

    @Override
    public void setSysDept(String guid, SysDeptDTO sysDept) {
        logger.info("设置组织机构缓存,guid:{}, sysDeptId:{}", guid, sysDept);
        if (StringUtils.isBlank(guid)) {
            return;
        }
        String value = JSONUtil.toString(sysDept);
        redisTemplate.opsForHash().put(SYS_DEPT_KEY, guid, value);
    }


    @Override
    public SysDeptDTO getSysDept(Integer deptId) {
        logger.info("获取组织机构缓存,deptId:{}", deptId);
        String val = String.valueOf(redisTemplate.opsForHash().get(SYS_DEPT_KEY, String.valueOf(deptId)));
        return JSONUtil.parseObject(val, SysDeptDTO.class);
    }

    @Override
    public SysDeptDTO getSysDept(String guid) {
        logger.info("获取组织机构缓存,guid:{}", guid);
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        String val = String.valueOf(redisTemplate.opsForHash().get(SYS_DEPT_KEY, guid));
        return JSONUtil.parseObject(val, SysDeptDTO.class);
    }

    @Override
    public void remove(Integer deptId) {
        logger.info("移除组织机构缓存,deptId:{}", deptId);
        redisTemplate.opsForHash().delete(SYS_DEPT_KEY, String.valueOf(deptId));
    }

    @Override
    public void remove(String guid) {
        logger.info("移除组织机构缓存,guid:{}", guid);
        if (StringUtils.isBlank(guid)) {
            return;
        }
        redisTemplate.opsForHash().delete(SYS_DEPT_KEY, guid);
    }

    @Override
    public boolean exists(Integer deptId) {
        return redisTemplate.opsForHash().hasKey(SYS_DEPT_KEY, String.valueOf(deptId));
    }
}
